//
//  SubscriptionViewController.m
//  FAKER
//
//  Created by Jianwei on 15/11/2.
//  Copyright © 2015年 YHLai. All rights reserved.
//

#import "SubscriptionViewController.h"
#import "AllHeader.h"
#import "BaseClassCollectionView.h"
#import "WFChannelPlateModel.h"
#import "FitHeader.h"
#import "WFChannelPlateCollectionViewCell.h"
#import "YHCirculationView.h"
#import "WFChannelDetailViewController.h"
#import "WFChannelWebViewController.h"
#define REPEAT_DATA_URLSTRING @"http://iphone.myzaker.com/zaker/follow_promote.php?_appid=iphone"
#define CHANNEL_PLATE_URLSTRING @"http://iphone.myzaker.com/zaker/apps_v3.php?_appid=iphone&_version=6.4&act=getAllAppsData"
@interface SubscriptionViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate, YHCirculationViewDelegate>
@property(nonatomic, strong)BaseClassCollectionView *plateCollectionView;
//@property(nonatomic, strong)BaseClassCollectionView *imageViewCollectionView;
@property(nonatomic, strong)NSMutableArray *repeatImageDataArray;
@property(nonatomic, strong)UIPageControl *pageControl;
@property(nonatomic, strong)NSArray *coreArray;
@property(nonatomic, strong)NSMutableArray *dataArray;
@property(nonatomic, strong)CoreDataManager *manager;
@property(nonatomic, strong)BaseClassView *navView;
@property(nonatomic, strong)UILabel *navLabel;
@end

@implementation SubscriptionViewController
#pragma mark 获取数据
- (void)getRepeatImageData
{
    [InternetDataRequest getDataByString:REPEAT_DATA_URLSTRING BodyDic:nil WithDataBlock:^(id data) {
        NSArray *array = [[data objectForKey:@"data"] objectForKey:@"list"];
        [self createCirculationView:array];
    }];
}
- (void)getChannelPlateData
{
    [InternetDataRequest getDataByString:CHANNEL_PLATE_URLSTRING BodyDic:nil WithDataBlock:^(id data) {
        NSArray *array = [[[[data objectForKey:@"data"] objectForKey:@"datas"] objectAtIndex:0] objectForKey:@"sons"];
        for (NSDictionary *dic in array) {
            if ([[dic objectForKey:@"title"] isEqualToString:@"中国日报网"] || [[dic objectForKey:@"title"] isEqualToString:@"中新网"] || [[dic objectForKey:@"title"] isEqualToString:@"九个头条"] || [[dic objectForKey:@"title"] isEqualToString:@"北京晚报"] || [[dic objectForKey:@"title"] isEqualToString:@"中新网军事"] || [[dic objectForKey:@"title"] isEqualToString:@"中华网军事"] || [[dic objectForKey:@"title"] isEqualToString:@"信网"] || [[dic objectForKey:@"title"] isEqualToString:@"中国网"] || [[dic objectForKey:@"title"] isEqualToString:@"凤凰新闻"]) {
                WFChannelPlateModel *model = [[WFChannelPlateModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                NewChannel *newChannel = [NSEntityDescription insertNewObjectForEntityForName:@"NewChannel" inManagedObjectContext:_manager.managedObjectContext];
                newChannel.title = model.title;
                newChannel.pic = model.pic;
                newChannel.block_color = model.block_color;
                newChannel.api_url = model.api_url;
                [_manager saveContext];
            }
        }
        [self getDataFromCoreData];
        [NSUSERDEFAULTS setBool:1 forKey:@"NewChannel"];
    }];
}
- (void)getDataFromCoreData
{
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"NewChannel"];
    _coreArray = [NSArray arrayWithArray:[_manager.managedObjectContext executeFetchRequest:fetchRequest error:nil]];
    _dataArray = [NSMutableArray arrayWithArray:_coreArray];
    [_plateCollectionView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"订阅";
    //    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18], NSForegroundColorAttributeName:[UIColor whiteColor]}];
}
- (void)changeColor
{
    if (NSUSERDEFAULTS_NIGHT) {
        _navView.backgroundColor = BGCOLOR_BLACK;
        _navLabel.textColor = [UIColor lightGrayColor];
    }
    else
    {
        _navView.backgroundColor = [UIColor colorWithRed:0.98 green:0.28 blue:0.28 alpha:1];
        _navLabel.textColor = [UIColor whiteColor];
    }
}
- (void)viewDidAppear:(BOOL)animated
{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}
- (void)loadView
{
    [super loadView];
    //初始化数据数组
    _manager = [CoreDataManager shareManager];
    _repeatImageDataArray = [NSMutableArray array];
    _coreArray = [NSArray array];
    ADD_NSNOTIFICATIONCENTER_OBSERVER;
    
    self.navigationController.navigationBar.hidden = 1;
    self.navigationController.automaticallyAdjustsScrollViewInsets = 0;
    self.automaticallyAdjustsScrollViewInsets = 0;
    
    UINavigationBar *navBar = self.navigationController.navigationBar;
    navBar.bounds = CGRectMake(0, 64, SCREEN_WIDTH, 64);
    
    
    _navView = [[BaseClassView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    [self.view addSubview:_navView];
    
    _navLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 20 * FITWIDTH, 22, 40 * FITWIDTH, 40)];
    _navLabel.textAlignment = 1;
    _navLabel.text = @"订阅";
    
    _navLabel.font = [UIFont fontWithBold:1 IPhone6sPlus:17 Iphone6s:17 Iphone5s:17 Iphone4s:17];
    [_navView addSubview:_navLabel];
    
    [self changeColor];
    
//    dispatch_queue_t mainQueue = dispatch_get_main_queue();
//    dispatch_async(mainQueue, ^{
//        [self getRepeatImageData];
//    });
    
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalQueue, ^{
        [self getRepeatImageData];
    });
    dispatch_async(globalQueue, ^{
        if ([NSUSERDEFAULTS boolForKey:@"NewChannel"] == 0) {
            [self getChannelPlateData];
        }
    });
    
    UICollectionViewFlowLayout *plateCollectionViewFlowLayout = [[UICollectionViewFlowLayout alloc]init];
    plateCollectionViewFlowLayout.itemSize = CGSizeMake((SCREEN_WIDTH - 4) / 3, (SCREEN_WIDTH - 4) / 3);
    plateCollectionViewFlowLayout.minimumInteritemSpacing = 1.5 * FITWIDTH;
    plateCollectionViewFlowLayout.minimumLineSpacing = 1.8 * FITWIDTH;
    plateCollectionViewFlowLayout.sectionInset = UIEdgeInsetsMake(210 * FITHEIGHT, 0, 0, 0);
    
    _plateCollectionView = [[BaseClassCollectionView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, /*(667 - 64 - 49) * FITHEIGHT*/SCREEN_HEIGHT - 64 - 49) collectionViewLayout:plateCollectionViewFlowLayout];
    _plateCollectionView.delegate = self;
    _plateCollectionView.dataSource = self;
    [_plateCollectionView registerClass:[WFChannelPlateCollectionViewCell class] forCellWithReuseIdentifier:@"plate"];
    [self.view addSubview:_plateCollectionView];
    [self getDataFromCoreData];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    WFChannelPlateCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"plate" forIndexPath:indexPath];
    cell.channelPlateModel = _dataArray[indexPath.row];
    cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
    [UIView animateWithDuration:0.5 animations:^{
        cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
    }];
    return cell;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _plateCollectionView) {
            WFChannelDetailViewController *wc = [[WFChannelDetailViewController alloc]init];
            wc.api_url = [_dataArray[indexPath.row] api_url];
            [wc setHidesBottomBarWhenPushed:1];
            [self.navigationController pushViewController:wc animated:1];
        }
}

- (void)createCirculationView:(NSArray *)array
{
    YHCirculationView *circulationView = [[YHCirculationView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 210 * FITHEIGHT) ImageDictArray:array];
    circulationView.circulationDelegate = self;
    [self.view addSubview:circulationView];
    [_plateCollectionView addSubview:circulationView];
}
#pragma mark - 轮播图跳转协议
- (void)passWebViewModel:(WFChannelDetailModel *)model
{
    [self.navigationController.navigationBar setHidden:YES];
    WFChannelWebViewController *webViewVC = [WFChannelWebViewController new];
    webViewVC.hidesBottomBarWhenPushed = YES;
    webViewVC.model = model;
    [self.navigationController pushViewController:webViewVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated
{
//    self.navigationController.navigationBar.hidden = 0;
}
@end
